package com.hundredapp.oa.util;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;

import com.hundredapp.oa.domain.OaAction;
import com.hundredapp.oa.repository.UserManager;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class ActionAspect {
	
	@Autowired
	private UserManager userManager;
	
	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
		Object retVal;
		Map<String, Object> session_map=ActionContext.getContext().getSession();
		HttpServletRequest request=   
				(HttpServletRequest)ActionContext.getContext() .get(ServletActionContext.HTTP_REQUEST);
		String uri= request.getRequestURI().substring(1);
		String action=uri.substring(uri.indexOf("/")+1);
		if(action.isEmpty()){
			action="index";
		}
		if(session_map.get("lgoin_user_id")!=null){
			int id=Integer.parseInt(session_map.get("lgoin_user_id").toString());
			List<OaAction> action_list=userManager.findAction(id);
			boolean flag=false;
			for(OaAction oaaction:action_list){
				if(action.startsWith(oaaction.getMappingAction())){
					flag=true;
				}
			}
			if(flag){
				retVal = pjp.proceed();
			}else{
				retVal="forbidden";
			}
		}else{
			session_map.put("prePage",action);
			retVal=ActionSupport.LOGIN;
		}
        return retVal;
    }

	public UserManager getUserManager() {
		return userManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	} 
}
